package com.superbytecode.cloud.redis.wrapper;

import lombok.experimental.UtilityClass;

import java.util.Stack;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: sanskrit
 * @Package: com.superbytecode.cloud.redis.wrapper
 * @ClassName: RedisCacheExpireHolder
 * @Description: [缓存过期Holder]
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/8/19 11:11
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.cn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@UtilityClass
public class RedisCacheExpireHolder {
    /**
     * 使用Stack适应方法嵌套的情况
     */
    private static final ThreadLocal<Stack<Long>> TIME_LOCAL = ThreadLocal.withInitial(Stack::new);

    /**
     * 获取当前方法失效时间（毫秒）
     */
    public static Long getCacheExpire() {
        Stack<Long> stack = TIME_LOCAL.get();
        // 使用peek方法而不是pop，因为在缓存命中时就不会执行到get方法
        return !stack.isEmpty() ? stack.peek() : null;
    }

    /**
     * 设置当前方法对应的缓存失效时间（毫秒）
     */
    public static void setCacheExpire(long milliseconds) {
        TIME_LOCAL.get().push(milliseconds);
    }

    /**
     * 移除
     */
    public static void removeCacheExpire() {
        Stack<Long> stack = TIME_LOCAL.get();
        stack.pop();
        if (stack.isEmpty()) {
            TIME_LOCAL.remove();
        }
    }
}